<template>
  <div class="home">
    <el-card>
      <div class="main">
        <div class="picture-show">
          <img v-if="filename" :src="url" alt="">
          <span v-else>图片预览区</span>
        </div>
        <!-- 上传图片 -->
        <div class="upload-btn">
          <el-button type="primary" @click="uploadPictrues">上传图片</el-button>
          <input style="display: none" type="file" id="file" ref="file" @click="e => {e.target.value = '';}" @change="uploadFile">
        </div>
      </div>
      
      <el-form inline class="copy-items">
        <el-form-item label="url" label-width="80px">
          <el-input v-model="url" autosize />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="copy-url" @click="copyItem('url')">复制</el-button>
        </el-form-item>
      </el-form>

      <el-form inline label-width="80px">
        <el-form-item label="markdown">
          <el-input v-model="markdown" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="copy-md" @click="copyItem('md')">复制</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- managerToken校验弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="491px"
      >
      <el-form inline>
        <el-form-item label="请输入管理员提供的密钥以解锁功能：">
          <el-input v-model="key" placeholder="请输入管理员提供的密钥" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitQiniuKey">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import * as qiniu from 'qiniu-js'
const QINIU_BASE_PATH = 'http://qiniu.cdn.yanwuhc.cn/'

export default {
  components: {},
  props: {},
  data() {
    return {
      url: '请选择上传图片',
      filename: '',
      token: '',
      key: '', // 静态密钥
      dialogVisible: true // 校验弹窗
    }
  },
  computed: {
    markdown() {
      if (this.filename && this.url) {
        return `![${this.filename}](${this.url})`
      } else {
        return '请选择上传图片'
      }
    },
    qiniuKey() {
      return this.$_constant.qiniu.key || ''
    }
  },
  created() {
    this.checkValidQiniuKey()
    this.getQiniuConfig()
    this.key = localStorage.getItem('TOKEN_KEY') || ''
  },
  methods: {
    checkValidQiniuKey() {
      const localKey = localStorage.getItem('TOKEN_KEY') || ''
      if (localKey) this.dialogVisible = false
    },
    submitQiniuKey() {
      if (this.key === this.qiniuKey) {
        localStorage.setItem('TOKEN_KEY', this.key)
        this.$notify.success({
          title: '成功',
          message: '密钥提交成功！'
        })
        this.dialogVisible = false
      } else {
        this.$notify.error({
          title: '无效密钥',
          message: '密钥不正确，请重新输入！'
        })
      }
    },
    // 上传图片
    uploadPictrues() {
      if (this.key !== this.qiniuKey) {
        return this.$notify.error({
          title: '无上传权限',
          message: '请刷新页面以重新输入密钥'
        })
      }
      this.$refs.file.dispatchEvent(new MouseEvent('click'))
    },
    // 上传到七牛云 - 具体实例
    async uploadFile() {
      const file = this.$refs.file.files[0]
      this.uploadToQiniu(file).then(res => {
        const { key } = res
        this.url = QINIU_BASE_PATH + key
        this.filename = file.name
        this.$notify.success({
          title: '成功',
          message: '上传成功！'
        })
      })
    },
    // 复制文字
    copyItem(selector) {
      switch (selector) {
        case 'url':
          this.copyMethod('.copy-url', this.url)
          break
        case 'md':
          this.copyMethod('.copy-md', this.markdown)
          break
      }
    },
    copyMethod (selector, item) {
      if (item === '请选择上传图片') {
        return this.$notify.error({
          title: '失败',
          message: '请先上传图片'
        })
      }
      let clipboard = new Clipboard (selector, {
        text: () => {
          return item
        }
      })
      clipboard.on('success', () => {
        this.$notify({
          type: 'success',
          title: '成功',
          message: '复制成功！'
        });
        clipboard.destroy()
      })
      clipboard.on('error', () => {
        this.$notify({
          type: 'error',
          title: '成功',
          message: '复制成功！'
        });
        clipboard.destroy()
      })
    },
    // 获取七牛云配置
    async getQiniuConfig() {
      const { data: { token } } = await this.$_api.getQiniuConfig()
      this.token = token
    },
    /**
     * @param file 文件对象
     * @param putExtra 上传的扩展信息
     * @param key 文件重命名
     * @description 封装 - 上传到七牛云
    */
    uploadToQiniu(file, putExtra = {}, key=undefined) {
      const token = this.token
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2
      };
      const observable = qiniu.upload(file, key, token, putExtra, config)
      return new Promise((resolve, reject) => {
        observable.subscribe(this.handleCallback(resolve, reject))
      })
    },
    handleCallback(resolve, reject) {
      return {
        next(res) {},
        error(error) {
          reject(error)
        },
        complete(res) {
          resolve(res)
        }
      }
    },
  }
}
</script>
<style scoped>
  /deep/ .el-input__inner {
    width: 450px;
  }
  /deep/ .el-dialog__body {
    padding: 0 20px;
  }
  .home {
    width: 100vw;
    height: 100vh;
    background-image: url('../../assets/bg.jpg');
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .main {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .picture-show {
    width: 500px;
    height: 400px;
    border: 1px dotted rgb(168, 168, 168);
    border-radius: 10px;
    overflow: hidden;
    text-align: center;
    line-height: 400px;
    color: rgb(168, 168, 168);
  }
  img {
    width: 500px;
    height: 400px;
  }
  .upload-btn {
    margin-left: 20px;
  }
  .copy-items {
    margin-top: 20px;
  }
</style>